#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h> 

#include "login.h"
#include "input_judge.h"
#include "debug.h"

int user_login(struct login_info *login_info_p)
{
	int8_t ret = 0;
	FILE *fp_login_info = NULL;
	struct login_info login_info_data;
	int ret_t = 0;

	if (!p_login_info) {
		DEBUG("PARAM ERROR!\n");
		return (-LOGIN_PARAM_NULL);
	}
	    
	/*判断账号输入格式*/
	ret = is_num_or_char(p_login_info->account);
	if (ret == FALSE) {
		printf("账号格式错误，由大小写字母或数字组成！\n");
		return FALSE;
	}
	
	/*判断密码格式*/
 	ret = is_num_or_char(p_login_info->password);
	if (ret == FALSE) {
	printf("密码格式错误，由大小写字母或数字组成！\n");
	return FALSE;
	}

	fp_login_info = fopen(LOGIN_FILE, "ab+");

	while (!feof(fp_login_info)) {
		fread(&login_info_data, sizeof(struct login_info), 1, fp_login_info);
		if (!strcmp(login_info_data.account, login_info_p->account)) {
			ret_t = TRUE;
			fclose(fp_login_info);
			break;
		}
	}
	fclose(fp_login_info);

	if (ret_t == 0) {
		printf("帐号不存在！");
		fclose (fp_login_info);
		return FALSE;
	}
	
	while (!feof(fp_login_info)) {
		fread(&login_info_data, sizeof(struct login_info), 1, fp_login_info);
		if ((!strcmp(login_info_data.account, login_info_p->account)) &&
			(!strcmp(login_info_data.password, login_info_p->password))){
				fclose(fp_login_info);
				return TRUE;
		}
	}
	fclose(fp_login_info);

	printf("密码错误！");
	return FALSE;
}

int user_register(struct login_info *login_info_p)
{
	int8_t ret = 0;
	FILE *fp_login_info = NULL;
	struct login_info login_info_data;

	if (!login_info_p) {
		DEBUG("PARAM ERROR!\n");
		return (-LOGIN_PARAM_NULL);
	}
	    
	if (strlen(login_info_p->account) == 0 ||
		strlen(login_info_p->password) == 0 ) {
				            
		printf("输入不能为空！\n");
		return FALSE;
	}

	/*判断账号格式*/
	ret = is_num_or_char(login_info_p->account);
	if (ret == FALSE) {
		printf("账号格式错误，由大小写字母或数字组成！\n");
		return FALSE;
	}

	/*判断密码格式*/
	ret = is_num_or_char(login_info_p->password);
	if (ret == FALSE) {
		printf("密码格式错误，由大小写字母或数字组成！\n");
		return FALSE;
	}

	fp_login_info = fopen(LOGIN_FILE, "ab+");

	while (!feof(fp_login_info)) {
		fread(&login_info_data, sizeof(struct login_info), 1, fp_login_info);
		if (!strcmp(login_info_data.account, login_info_p->account)) {
			printf("帐号已被注册！");
			return FALSE;
		}
	}

	fclose(fp_login_info);

	fwrite(login_info_p, sizeof(struct login_info), 1, fp_login_info);
	fclose(fp_login_info);

	login_info_p->is_login = 1;
	return TRUE;
}


int user_logout(struct login_info *login_info_p) 
{
	if (!login_info_p) {
		DEBUG("PARAM ERROR!\n");
		return (-LOGIN_PARAM_NULL);
	}
			    
	if(login_info_p->is_login != 1)
		return FALSE;

	login_info_p->is_login = 0;
	memset(login_info_p->enter_password, '\0', PASSWORD_LENGTH);
	memset(login_info_p->account, '\0', ACCOUNT_LENGTH);
	memset(login_info_p->password, '\0', PASSWORD_LENGTH);

	return TRUE;
}
